<?php
namespace app\index\controller;

use app\common\model\Admin;
use app\common\model\attendDid;
use app\common\model\Department;
use app\common\model\DepartmentAdmin;
use app\common\model\Position;
use think\Db;

class Index
{
    private $attendDidModel; // 临时部门表
    private $departmentModel; // 部门表
    private $adminModel; // 员工表
    private $positionModel; // 岗位表
    private $departmentAdminModel; // 次级部门表
    public function __construct()
    {
        $this->attendDidModel = new attendDid();
        $this->departmentModel = new Department();
        $this->adminModel = new Admin();
        $this->departmentAdminModel = new DepartmentAdmin();
        $this->positionModel = new Position();
    }

    public function index()
    {
        $DidList = $this->attendDidModel->select();

        // 存储需要插入的数据和删除的数据
        $insertData = [];
        $delData = [];

        // 提前获取所有的 admin_id
        $adminIds = [];
        foreach ($DidList as $item) {
            $adminIds[] = $this->getAminId($item['person_name']);
        }

        // 提前获取所有的 did
        $adminDids = [];
        foreach ($DidList as $item) {
            $parentId = $this->getDid($item['did_name_path']);
            $adminDids[] = $parentId;
        }

        // 提前获取所有的 position_id
        $positionIds = [];
        foreach ($DidList as $item) {
            $positionIds[] = $this->getPositionId($item['position_name']);
        }

        // 获取所有的 department_id
        $departmentIds = [];
        foreach ($DidList as $item) {
            $departments = explode('-', $item['did_name_path']);
            $parentId = $this->getPid($departments);
            $departmentIds[] = $parentId;
        }

        // 获取所有admin_id 和 department_id对应的删除数据
        foreach ($DidList as $key => $item) {
            $AminId = $adminIds[$key];
            $PositionId = $positionIds[$key];
            $parentId = $departmentIds[$key];
            $dId = $adminDids[$key];
            if (!empty($AminId)) {
                $editData[] = [
                    'id' => $AminId,
                    'position_id' => $PositionId,
                    'sex' => $item['sex'],
                    'did' => $dId,
                    'entry_time' => $item['entry_time'],
                    'mobile' => $item['mobile']
                ];

                $insertData[] = [
                    'admin_id' => $AminId,
                    'create_time' => time(),
                    'department_id' => $parentId,
                ];

                $delData[] = [
                    'admin_id' => $AminId,
                    'department_id' => $parentId,
                ];
            }
        }
//        'person_name' => $item['person_name'],
//
//        return json(['status' => 'error', 'message' => $editData])->code(200);

        // 开启事务
        $this->departmentAdminModel->startTrans();
        $this->adminModel->startTrans();
        try {
            // 批量删除
            if (!empty($delData)) {

                // 生成符合删除条件的 admin_id 和 department_id 数组
                $delIdsAdmin = array_map(function($v) {
                    return $v['admin_id'];
                }, $delData);
                $delIdsDepartment = array_map(function($v) {
                    return $v['department_id'];
                }, $delData);

                // 根据 admin_id 和 department_id 删除
                $delcount = $this->departmentAdminModel
                    ->whereIn('admin_id', $delIdsAdmin)
                    ->whereIn('department_id', $delIdsDepartment)
                    ->delete();

            }

            // 批量修改
            if (!empty($editData)) {
                $result = $this->adminModel->saveAll($editData);
                if($result > 0){
                    $editcount = count($editData);
                }
            }

            // 批量插入
            if (!empty($insertData)) {
                $count = $this->departmentAdminModel->limit(100)->insertAll($insertData);
            }

            // 提交事务
            $this->departmentAdminModel->commit();
            $this->adminModel->commit();
        } catch (\Exception $e) {
            // 出现错误时回滚事务
            $this->departmentAdminModel->rollback();
            $this->adminModel->rollback();
            return json(['status' => 'error', 'message' => '操作失败，错误信息：' . $e->getMessage()])->code(500);
        }

        return json(['status' => 'success', 'message' => '操作成功', 'data' => '共成功导入了' . $count . '条数据，删除了' . $delcount . '条数据，修改了' . $editcount . '条数据'])->code(200);
    }

    public function getAminId($name)
    {
        // 提前查询所有管理员的id，避免每次查询
        static $adminCache = [];
        if (isset($adminCache[$name])) {
            return $adminCache[$name];
        }

        $adminId = $this->adminModel->where('name', $name)->value('id');
        $adminCache[$name] = $adminId;
        return $adminId;
    }

    public function getPositionId($name)
    {
        // 提前查询所有岗位的id，避免每次查询
        static $positionCache = [];
        if (isset($positionCache[$name])) {
            return $positionCache[$name];
        }

        $positionId = $this->positionModel->where('title', $name)->value('id');
        $positionCache[$name] = $positionId;
        return $positionId;
    }

    // 获取主部门id
    public function getDid($departments)
    {
        $didId = 0;  // 从根部门（parent_id = 0）开始
        // 使用 explode() 按照 "-" 分割字符串
        $array = explode("-", $departments);

        // 确保数组至少有两个元素
        $count = count($array);
        for ($i = 0; $i < min(2, $count); $i++) {
            $department = $array[$i];
            // 查找当前层级的部门 ID
            $departmentId = $this->departmentModel->where('title', $department)->where('pid', $didId)->value('id');
            // 如果没有找到该部门，返回 null
            if (!$departmentId) {
                return null;
            }
            // 更新父级 ID，为下一层级查询做准备
            $didId = $departmentId;
        }
        return $didId;
    }


    // 获取次级部门id
    public function getPid($departments)
    {
        $parentId = 0;  // 从根部门（parent_id = 0）开始
        foreach ($departments as $department) {
            // 查找当前层级的部门 ID
            $departmentId = $this->departmentModel->where('title', $department)->where('pid', $parentId)->value('id');
            // 如果没有找到该部门，返回 null
            if (!$departmentId) {
                return null;
            }
            // 更新父级 ID，为下一层级查询做准备
            $parentId = $departmentId;
        }
        return $parentId;
    }
}
